package Controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.*;

import Bean.BeanOrder;
import Impl.OrderServiceImpl;

import exception.BooksNotFoundException;



@Controller
public class ShowOrderController {
	OrderServiceImpl orderService;
	

    @RequestMapping("/ShowOrder")
	protected void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
    	response.setContentType("text/html;charset=UTF-8");  
    	JSONArray arr = new JSONArray();
    	ApplicationContext applicationContext=(ApplicationContext)request.getSession().getServletContext().getAttribute("ctx");
        orderService=(OrderServiceImpl)applicationContext.getBean("OrderServiceImpl");
		Collection<BeanOrder> orders;
		ArrayList<BeanOrder> my_order=new ArrayList<>();
		String userid=request.getParameter("userid");
		try {
			orders = orderService.getOrders((String)request.getSession().getAttribute("userid"));
			for(BeanOrder o:orders) {
				my_order.add(o);
				arr.add(o.toJson());
			}
		} catch (BooksNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		response.getWriter().append(arr.toJSONString());
		response.getWriter().append(JSON.toJSONString(my_order, SerializerFeature.DisableCircularReferenceDetect));
	}
}
